package com.hw.servlet;

import com.google.gson.Gson;
import com.hw.dao.BookUsDao;
import com.hw.entity.BookUsers;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;utf-8");
        String user=request.getParameter("user");
        String possword=request.getParameter("possword");
        PrintWriter printWriter = response.getWriter();
        HashMap<String,String> stringStringHashMap = new HashMap<>();
        HttpSession session=request.getSession();
        Gson gson=new Gson();
        boolean t=true;
        if (isBookU(user,possword)){


            stringStringHashMap.put("code","1");
            session.setAttribute("code",t);
            session.setAttribute("account",user);
            printWriter.write(gson.toJson(stringStringHashMap));
        }else {
            stringStringHashMap.put("code","0");
            session.setAttribute("code",!t);
            printWriter.write(gson.toJson(stringStringHashMap));
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
    public boolean isBookU(String account,String password){
        BookUsDao bookUsDao=new BookUsDao();
        List<BookUsers> aus=bookUsDao.findAll();
        BookUsers bookUser=new BookUsers(account,password);
        return aus.contains(bookUser);

    }
}
